package com.springcloudlearn.hystrix;

import com.netflix.hystrix.HystrixCommand;
import org.springframework.web.client.RestTemplate;

/**
 * @Package: com.springcloudlearn.hystrix
 * @ClassName: :MyHystrixCommand
 * @Description: springcloud-learn
 * @Author: Coding-Farmer
 * @Date: 2019/8/6 18:19
 */
public class MyHystrixCommand extends HystrixCommand<String> {

    private RestTemplate restTemplate;

    public MyHystrixCommand(Setter setter,RestTemplate restTemplate){
        super(setter);
        this.restTemplate=restTemplate;
    }

    /**
     * 当远程服务超时、异常、不可用等情况会触发熔断方法
     * @return
     * @throws Exception
     */
    @Override
    protected String run() throws Exception {
        //调用远程的服务
        return   restTemplate.getForEntity("http://SPRINGCLOUD-SERVICE-PROVIDER/provider/hello",String.class).getBody();
    }

    @Override
    public String getFallback(){
        //调用getExecutionException()方法来获取服务抛出的异常
        System.out.println("异常信息为："+getExecutionException().getMessage());
        //实现服务熔断/降级逻辑
        return "error";
    }
}
